package com.fzrskj.cloud.free.miniservice.utils;

import com.fzrskj.cloud.free.core.WiniisCacheImplMain;
import com.fzrskj.cloud.free.miniservice.service.vo.MiniServiceTokenBean;
import com.winiis.component.cache.core.CacheUtils;
import ms.core.object.CObject;

import java.util.UUID;

/**
 * MiniServicePublicUtils.
 *
 * @author zj.
 *         Created on 2019/5/23 0023.
 */
public class MiniServiceTokenUtils extends CObject {
    final private String cacheKey = "MT:{uuid}";
    final private Long tokenValidity = 24 * 60 * 60 * 1000L;
    /**
     * 生成Token.
     * @param serverCode 服务编码.
     * @return token.
     */
    public MiniServiceTokenBean createToken(String serverCode) {
        //缓存数据
        MiniServiceTokenBean tokenBean = new MiniServiceTokenBean();
        tokenBean.setToken(UUID.randomUUID().toString());
        tokenBean.setServerCode(serverCode);
        tokenBean.setExpireAt(System.currentTimeMillis() + this.tokenValidity);
        tokenBean.setType(1);
        //缓存key
        String cacheKey = this.cacheKey.replaceAll("\\{uuid}", tokenBean.getToken());
        //生成缓存
        CacheUtils cacheUtils = new CacheUtils(new WiniisCacheImplMain());
        cacheUtils.set(cacheKey, tokenBean, (int) (tokenValidity / 1000));
        //返回
        return tokenBean;
    }

    public MiniServiceTokenBean createToken(String serverCode,Integer userId) {
        //缓存数据
        MiniServiceTokenBean tokenBean = new MiniServiceTokenBean();
        tokenBean.setToken(UUID.randomUUID().toString());
        tokenBean.setServerCode(serverCode);
        tokenBean.setUserId(userId);
        tokenBean.setType(2);
        tokenBean.setExpireAt(System.currentTimeMillis() + this.tokenValidity);
        //缓存key
        String cacheKey = this.cacheKey.replaceAll("\\{uuid}", tokenBean.getToken());
        //生成缓存
        CacheUtils cacheUtils = new CacheUtils(new WiniisCacheImplMain());
        cacheUtils.set(cacheKey, tokenBean, (int) (tokenValidity / 1000));
        //返回
        return tokenBean;
    }

    /**
     * 获取token.
     * @param token token.
     * @param refresh 是否更新.
     * @return token info
     */
    public MiniServiceTokenBean getToken(String token, Integer refresh) {
        //缓存key
        String cacheKey = this.cacheKey.replaceAll("\\{uuid}", token);
        //获取数据
        CacheUtils cacheUtils = new CacheUtils(new WiniisCacheImplMain());
        MiniServiceTokenBean tokenBean = cacheUtils.get(cacheKey);
        if (null != tokenBean && 1 == refresh) {
            //清除原token
            cacheUtils.delete(cacheKey);
            //生成新token.
            tokenBean = this.createToken(tokenBean.getServerCode());
        }
        return tokenBean;
    }
}
